<template>
  <el-table ref="table" :data="specExt" border stripe style="width: 100%">
    <el-table-column prop="sku" label="SKU" />
    <el-table-column v-for="(item, index) in productVo.attrs" :key="index" :label="item.name">
      <template #default="scope">
        {{ scope.row.productSpecAttrs.find(attr => attr.attrId === item.id)?.attrValue }}
      </template>
    </el-table-column>
    <el-table-column prop="quantity" label="库存" />
    <el-table-column prop="price" label="售价" width="120">
      <template #header>
        售价
        <el-input v-if="isNew" v-model="quickPrice" size="small" style="width: 50px" />
      </template>
      <template #default="scope">
        <el-input v-model="scope.row.specInfo.price" />
      </template>
    </el-table-column>
    <el-table-column label="上架" prop="saleStatus">
      <template #default="scope">
        <el-switch
          v-model="scope.row.specInfo.saleStatus"
          :active-value="1"
          :inactive-value="0"
          active-text="是"
          inactive-text="否"
          inline-prompt
        />
      </template>
    </el-table-column>
  </el-table>
</template>
<script setup lang="ts">
import { ref, shallowRef, PropType, useTemplateRef, reactive, watch } from "vue";
interface ShopProductSpecDetailVoUse extends ShopProductSpecDetailVo {
  specInfo: ShopGoodsAddSpecVo;
}
const specInfos = defineModel({ type: Object as PropType<ShopGoodsAddSpecVo[]>, required: true });
const { productVo } = defineProps({
  productVo: {
    type: Object as PropType<ShopProductDetailVo>,
    required: true
  }
});
const quickPrice = ref<number>();
const table = useTemplateRef("table");
const isNew = specInfos.value.length == 0;
let map = new Map<number, ShopGoodsAddSpecVo>();
if (specInfos.value.length > 0) {
  specInfos.value.forEach(spec => {
    map.set(spec.productSpecId, spec);
  });
} else {
  productVo.specs.forEach(spec => {
    let specInfo: ShopGoodsAddSpecVo = reactive({
      productSpecId: spec.id,
      price: 0,
      saleStatus: 1
    });
    map.set(spec.id, specInfo);
    specInfos.value.push(specInfo);
  });
  watch(quickPrice, newPrice => {
    if (newPrice) {
      specInfos.value.forEach(spec => {
        spec.price = newPrice;
      });
    }
  });
}

let specExt: ShopProductSpecDetailVoUse[] = productVo.specs.map(spec => ({
  ...spec,
  specInfo: map.get(spec.id)
}));
</script>
